package com.mtons.mblog.base.utils;

import com.mtons.mblog.base.model.result.ResultResponse;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Hibernate 校验工具类
 */
public class ValidateUtils {

    private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

    public static <T> List<String> validate(T t) {
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);

        List<String> messageList = new ArrayList<>();
        for (ConstraintViolation<T> constraintViolation : constraintViolations) {
            messageList.add(constraintViolation.getMessage());
        }

        return messageList;
    }


    public static <T> ResultResponse validateAndAdvice(T t) {
        List<String> validateList = validate(t);
        if (validateList != null && !validateList.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (String message : validateList) {
                sb.append(message + " ");
            }
            return  ResultResponse.error(sb.toString());
        }else {
            return null;
        }
    }
}
